﻿using System;
using System.Web.UI.WebControls;

namespace Ue.Extensions
{
    public static class ListControlExtensions
    {
        #region 绑定ListControl控件

        public static void DataBindingByDataSource(this ListControl listControl, object dataSource)
        {
            listControl.DataBindingByDataSource(dataSource, 0);
        }
        public static void DataBindingByDataSource(this ListControl listControl, object dataSource, int selectIndex)
        {
            listControl.DataBindingByDataSource(dataSource, string.Empty, string.Empty, selectIndex);
        }
        public static void DataBindingByDataSource(this ListControl listControl, object dataSource, string selectValue)
        {
            listControl.DataBindingByDataSource(dataSource, string.Empty, string.Empty, selectValue);
        }
        public static void DataBindingByDataSource(this ListControl listControl, object dataSource, string dataValueField, string dataTextField, int selectIndex)
        {
            listControl.DataBindingByDataSource(dataSource, dataValueField, dataTextField, control =>
            {
                return control.Items[selectIndex];
            });
        }
        public static void DataBindingByDataSource(this ListControl listControl, object dataSource, string dataValueField, string dataTextField, string selectValue)
        {
            listControl.DataBindingByDataSource(dataSource, dataValueField, dataTextField, control =>
            {
                return control.Items.FindByValue(selectValue);
            });
        }
        public static void DataBindingByDataSource(this ListControl listControl, object dataSource, string dataValueField, string dataTextField, Func<ListControl, ListItem> acquireSelectItemAction)
        {
            if (listControl == null)
            {
                throw new ArgumentNullException("listControl");
            }

            if (acquireSelectItemAction == null)
            {
                throw new ArgumentNullException("acquireSelectItemAction");
            }

            if (dataSource != null)
            {
                listControl.DataSource = dataSource;

                if (!string.IsNullOrEmpty(dataValueField))
                {
                    listControl.DataValueField = dataValueField;
                }

                if (!string.IsNullOrEmpty(dataTextField))
                {
                    listControl.DataTextField = dataTextField;
                }

                listControl.DataBind();

                ListItem item = acquireSelectItemAction(listControl);
                if (item != null)
                {
                    item.Selected = true;
                }
            }
        }

        #endregion
    }
}
